package com.neusoft.cmsprojects.dao;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.neusoft.cmsprojects.model.Privilege;
import com.neusoft.cmsprojects.util.DaoUtilImpl;

@Repository("privilegedao")

public class PrivilegeDaoImpl extends DaoUtilImpl implements PrivilegeDao {

	@Resource(name="sessionFactory")
	private SessionFactory sf;
	
	
	@SuppressWarnings("unchecked")
	public List<Privilege> findTopPrivilege() {
		List<Privilege> list=(List<Privilege>)this.getHibernateTemplate().find("from Privilege as p where p.parent is null order by p.id ");
		return list;
	}

	@Override
	public Collection<String> getAllPrivilegeUrls() {
		Collection<String> st=(Collection<String>)this.getHibernateTemplate().find("SELECT DISTINCT p.url FROM Privilege p WHERE p.url IS NOT NULL order by p.id");
		return st;
	}

	@Override
	public List<Privilege> getByIds(Integer[] privilegeIds) {
		if (privilegeIds == null || privilegeIds.length == 0) {
			return Collections.EMPTY_LIST;
		} else {
			
			Session session=sf.getCurrentSession();
			return (List<Privilege>)session.createQuery("FROM  Privilege WHERE id IN (:ids)")
			.setParameterList("ids", privilegeIds)
			.list();
			
		}
		
	}

	@Override
	public List<Privilege> findPrivilegeById(Integer id) {
		Session session=sf.getCurrentSession();
		return (List<Privilege>)session.createQuery("from Privilege p join p.role r where r.id="+id+" ").list();
	}

	@Override
	public Privilege getById(Integer parentId) {
	
		return this.getHibernateTemplate().get(Privilege.class, parentId);
	}

	@Override
	public List<Privilege> findChildren(String hql) {
		return (List<Privilege>)this.getHibernateTemplate().find(hql);
	}

	@Override
	public void deleteAndRole(Privilege privilege) {
		Session session=sf.getCurrentSession();
		String sql="delete from privilage_role  where privilegeid="+privilege.getId();
		SQLQuery query=session.createSQLQuery(sql);
		query.executeUpdate();
		this.delete(privilege);
	}

	

}
